package com.mars.controller;

import com.mars.po.LoginForm;
import com.mars.po.User;
import com.mars.service.UserService;
import com.mars.validate.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private UserValidator validator;
    /**
     * 登录
     * @param loginForm
     * @param model
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String Login(@ModelAttribute("loginForm") LoginForm loginForm, Model model, HttpServletRequest request,HttpSession session) {
        if (request.getMethod().equals("POST")){
            //todo:validate form date
            if (userService.login(loginForm)){
                session.setAttribute("islogin",1);
                User user = userService.findByEmail(loginForm.getEmail());
                session.setAttribute("user",user);
                System.out.println(user.getProducts());
                return "redirect:index";
            }
            model.addAttribute("error","用户名或密码错误");
        }
        return "user/login";
    }

    /**
     * 注册
     * @param user
     * @param model
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/registe")
    public String Registe(@ModelAttribute("user") User user, Model model, HttpServletRequest request, HttpSession session, BindingResult result) {
        if (request.getMethod().equals("POST")) {
            //todo:validate form date
            this.validator.validate(user, result);
            if (result.hasErrors()){
                return "user/registe";
            }
            userService.registe(user);
            System.out.println(user.getProducts());
            session.setAttribute("islogin", 1);
            session.setAttribute("user", user);
            return "redirect:index";
        }
        return "user/registe";
    }

    @RequestMapping("/index")
    public String Index(Model model) {
        model.addAttribute("users",userService.getAll());
        return "user/index";
    }

    @RequestMapping("/view")
    public String View(Model model,int id) {
        model.addAttribute("user",userService.findById(id));
        return "user/view";
    }

}
